<?php
include_once 'root.php';
Class Order extends Root {
	public function __construct() {

		parent::__construct();

		$this -> load -> helper('util');
	}

	public function index() {
		$this -> data['header'] = "เลือกประเภทเอกสาร";
		$this -> includeView("docaction");
	}

	public function selectCustType() {
		$this -> data['header'] = "ประเภทลูกค้า";
		$this -> includeView("selectcust");
	}

	public function selectCustomer() {
		$this -> data['header'] = "เลือกลูกค้า";

		$this -> data['canSearch'] = $this -> canUseFunction("customer", "search");
		$this -> data['canCheckIn'] = $this -> canUseFunction("customer", "edit");

		$this -> load -> model("customermodel");
		$q = $this -> getCoreQuery(true);
		if (!empty($q)) {
			$allRow = $this -> customermodel -> getCustomerCount($this -> checkIDSearch("customer", "viewall"), $q);
			$this -> data['dataList'] = $this -> customermodel -> getCustomer($this -> checkIDSearch("customer", "viewall"), $q, 0, 50);
		}
		$this -> includeView("selectcustomerorder");
	}

	public function create() {
		$this -> data['header'] = "เลือกลูกค้า";

		$this -> data['canSearch'] = $this -> canUseFunction("customer", "search");
		$this -> data['canCheckIn'] = $this -> canUseFunction("customer", "edit");

		$this -> load -> model("customermodel");
		$q = $this -> getCoreQuery(true);
		$allRow = $this -> customermodel -> getCustomerCount($this -> checkIDSearch("customer", "viewall"), $q);
		$this -> data['dataList'] = $this -> customermodel -> getCustomer($this -> checkIDSearch("customer", "viewall"), $q, 0, 50);

		$this -> includeView("startcreateorder");
	}

	public function tocreate($custID) {
		$this -> cart -> destroy();

		$this -> session -> set_userdata('order_type', "");
		$action = (isset($_GET['action'])) ? $_GET['action'] : "first";
		$this -> data['action'] = $action;
		$this -> load -> model("customermodel");
		$this -> load -> model("ordermodel");
		$this -> load -> library('genhtml');

		$this -> data['genhtml'] = $this -> genhtml;
		$customerData = $this -> customermodel -> getACustomer($custID, $this -> checkIDSearch("customer", "viewall"));

		$this -> data['dataList'] = $customerData;
		if ($this -> data['dataList'] != false) {

			$this -> data['priceType'] = $this -> ordermodel -> getPriceType();

			$this -> session -> set_userdata("currentcustomer", $custID);
			$this -> data['header'] = "เปิด order ลูกค้า " . $customerData -> NAME;
			$this -> genhtml -> setData($this -> data['dataList']);
		}

		$this -> includeView("createordercustomer");
	}

	public function editOrder($orderID) {

		$this -> load -> model("ordermodel");
		$this -> data['order'] = $this -> ordermodel -> getOrderView($orderID);
		$this -> load -> library('genhtml');
		$this -> data['genhtml'] = $this -> genhtml;
		$this -> session -> set_userdata("CORDERID", $orderID);
		if ($this -> data['order'] != false) {
			$this -> data['header'] = "เปิด order ลูกค้า " . $this -> data['order'] -> CustName;
			$this -> session -> set_userdata("currentcustomer", $this -> data['order'] -> CustID);
			$this -> session -> set_userdata("currentOrderID", $orderID);
			if ($this -> data['order'] -> Payment == "Cash") {
				$this -> data['order'] -> Payment = "เงินสด";
			}
			if ($this -> data['order'] -> CustType == "WholeSale") {
				$this -> data['order'] -> CustType = "Whole Sale";
			}
			$this -> data['order'] -> CreditRemainFormat = number_format($this -> data['order'] -> CreditRemain, 2);
			$this -> genhtml -> setData($this -> data['order']);
		}

		$this -> includeView("editorder");
	}

	public function deleteOrder() {
		$orderID = $_POST['id'];
		$this -> load -> model("ordermodel");
		$delete = $this -> ordermodel -> deleteOrder($orderID);
		if ($delete) {
			$this -> set_res("true", "ลบข้อมูลเรียบร้อยแล้ว");
		} else {
			$this -> set_res("true", "ไม่สามารถลบเอกสารได้");
		}
	}

	public function removeorder() {
		$id = $_POST['index'];
		$data = array('rowid' => $id, 'qty' => 0);

		$this -> cart -> update($data);
		echo json_encode(array("flag" => true, "message" => "ไม่พบข้อมูลสินค้า"));
	}

	public function status() {

		$flag = (isset($_GET['flag'])) ? $_GET['flag'] : "C";

		if ($flag == "C") {
			$str = "Completed";
		} elseif ($flag == "C") {
			$str = "Failed";
		} else {
			$str = "All";
		}

		$this -> checkAuthen("order", "view");
		$this -> data['header'] = "Order Status " . $str;
		$this -> load -> model("reportmodel");

		$allRow = $this -> reportmodel -> getOrderStatusCount($flag);
		$pageConfig = $this -> initPagination($allRow);
		;
		$this -> data['pagination'] = $this -> pagination;

		$data = $this -> reportmodel -> getOrderStatus($flag, $pageConfig['start'], $pageConfig['limit']);
		$this -> data['dataList'] = $data;
		$this -> data['flag'] = $flag;
		$this -> includeView("orderstatus");

	}

	public function returnOrder() {
		$this -> includeView("wait");
	}

	public function seachproduct() {
		$keyword = $_POST['keyword'];
		$vatType = $_POST['vatType'];
		$priceType = $_POST['priceType'];
		$column = "";
		$unit = "";
		if ($priceType == "ZPR0") {
			$column = "CREDIT_" . $vatType . "_PRICE";
			$unit = "CREDIT_" . $vatType . "_UNIT";
		} else if ($priceType == "ZPR1") {
			$column = "VAN_" . $vatType . "_PRICE";
			$unit = "VAN_" . $vatType . "_UNIT";
		}

		if ($keyword == "") {
			echo json_encode(array("flag" => false, "message" => "กรอกข้อมูล"));
			exit();
		}

		$this -> load -> model("productmodel");
		$data = $this -> productmodel -> searchProductPrice($keyword, $column, $unit);

		if (!empty($data)) {
			$dataCart = $this -> in_cart();
			foreach ($data as $in => $val) {
				if (array_key_exists($val -> MATNR, $dataCart)) {
					$currentSelect = $dataCart[$val -> MATNR];
					$val -> qty = $currentSelect['qty'];
					$val -> rowid = $currentSelect['rowid'];
				} else {
					$val -> qty = 0;
					$val -> rowid = 0;
				}

				$pricePer = $val -> $unit;
				$p = explode("/", $pricePer);
				$priceUnit = $p[1];
				$ratio = 1;

				$baseUnit = $val -> BASE_UNIT;

				if ($priceUnit == "CAR") {
					$ratio = $val -> EA_CARTON;
				} else if ($priceUnit == "PAC") {
					$ratio = $val -> EA_PACK;
				} else if ($priceUnit == "CAN") {
					$ratio = 1;
				} else {
					$ratio = 1;
				}
				$val -> DisplayPrice = number_format($val -> $column / $ratio, 2, '.', '');
				$val -> CalPrice = number_format($val -> $column / $ratio, 4, '.', '');
			}

			echo json_encode(array("flag" => true, "message" => $data));

		} else {

			echo json_encode(array("flag" => false, "message" => "ไม่พบข้อมูลสินค้า"));
			exit();
		}
	}

	public function seachproductPromotion() {
		$keyword = $_POST['keyword'];
		$promotionID = $_POST['promotionID'];
		$priceType = $_POST['priceType'];
		$priceTypeUnit = $_POST['priceTypeUnit'];
		if ($keyword == "") {
			echo json_encode(array("flag" => false, "message" => "กรอกข้อมูล"));
			exit();
		}

		$this -> load -> model("productmodel");
		$data = $this -> productmodel -> searchProductPromotion($keyword, $priceType, $promotionID);

		if (!empty($data)) {
			$dataCart = $this -> in_cartPemium();

			foreach ($data as $in => $val) {
				if ($dataCart != "") {
					if (array_key_exists($val -> MATNR, $dataCart)) {
						$currentSelect = $dataCart[$val -> MATNR];
						$val -> qty = $currentSelect['qty'];
						$val -> rowid = $currentSelect['rowid'];
					} else {
						$val -> qty = 0;
						$val -> rowid = 0;
					}
				} else {
					$val -> qty = 0;
					$val -> rowid = 0;
				}

				$pricePer = $val -> $priceTypeUnit;
				$p = explode("/", $pricePer);
				$priceUnit = $p[1];
				$ratio = 1;

				$baseUnit = $val -> BASE_UNIT;

				if ($priceUnit == "CAR") {
					$ratio = $val -> EA_CARTON;
				} else if ($priceUnit == "PAC") {
					$ratio = $val -> EA_PACK;
				} else if ($priceUnit == "CAN") {
					$ratio = 1;
				} else {
					$ratio = 1;
				}
				$val -> DisplayPrice = number_format($val -> $priceType / $ratio, 2, '.', '');
				$val -> CalPrice = number_format($val -> $priceType / $ratio, 4, '.', '');
			}

			echo json_encode(array("flag" => true, "message" => $data));

		} else {

			echo json_encode(array("flag" => false, "message" => "ไม่พบข้อมูลสินค้า"));
			exit();
		}
	}

	public function checkdata() {
		echo $this -> cart -> total_items();

	}

	public function addpromotion() {
		$this->checkOrderNotEmpty();
		//$this -> deletePremium();
		$this -> load -> library('genhtml');
		$this -> load -> model("ordermodel");
		$this -> load -> model("promotionmodel");
		$orderID = $this -> session -> userdata("CORDERID");
		$order = $this -> ordermodel -> getOrderHead($orderID);
		$this -> data['order'] = $order;

		$vatType = $order -> VatType;
		$priceType = $order -> PriceTypeID;
		if ($priceType == "ZPR0") {
			$column = "CREDIT_" . $vatType . "_PRICE";
			$unit = "CREDIT_" . $vatType . "_UNIT";
		} else if ($priceType == "ZPR1") {
			$column = "VAN_" . $vatType . "_PRICE";
			$unit = "VAN_" . $vatType . "_UNIT";
		}
		$this -> data['PRICE_COLUMN'] = $column;
		$this -> data['PRICE_COLUMN_UNIT'] = $unit;

		$this -> data['header'] = "สรุปรายการสั่งซื้อ";
		$custID = $this -> session -> userdata("currentcustomer");
		$this -> data['orderType'] = $this -> ordermodel -> getOrderType();
		$this -> data['orderReason'] = $this -> ordermodel -> getOrderReason();
		$this -> data['itemCategory'] = $this -> ordermodel -> getItemCategory();
		$this -> data['priceType'] = $this -> ordermodel -> getPriceType();

		$this -> data['genhtml'] = $this -> genhtml;
		$this -> load -> model("customermodel");

		$customerData = $this -> customermodel -> getACustomer($custID, "");

		if ($this -> session -> userdata('order_type') == "") {
			foreach ($_POST as $in => $val) {
				$this -> session -> set_userdata($in, $_POST[$in]);
			}
		}
		$priceType = $order -> PriceTypeID;

		$intPriceType = preg_replace("/[^0-9,.]/", "", $priceType);

		$myCart = $this -> cart -> contents();
		$i = 0;
		$sumOfPromotion = array();
		foreach ($this->cart->contents() as $items) {
			if ($items['price'] > 0) {
				// หาก่อนว่าสินค้าโปรโมชั่นนี้ ได้รับโปรโมชั่นหรือเปล่า
				$data = $this -> promotionmodel -> getPromotionByMatnr($items['id']);

				// ข้อมูลของสินค้า
				$option = $this -> cart -> product_options($items['rowid']);
				if (!isset($option["ISPremium"])) {
					// ถ้าสินค้านี้ได้รับโปรโมชั่น
					if ($data != false && $option[$unit] != "") {
						foreach ($data as $j => $k) {

							$promotion = $this -> promotionmodel -> getPromotionByPriceType($k -> PROMO_ID, $intPriceType);

							$ratio = $option['EA_CARTON'] / $option['EA_PACK'];
							$numSelect = $items['qty'] / $ratio;
							$ratioGroup = $numSelect / $ratio;
							$unique = $k -> PROMO_ID;
							if (!isset($sumOfPromotion[$unique])) {
								$sumOfPromotion[$unique]['NUMADD'] = $ratioGroup;
								$sumOfPromotion[$unique]['NUMADDALL'] = $numSelect;

								if (isset($promotion -> promotionList)) {
									$promotion -> promotionList;
									$sumOfPromotion[$unique]['PRODUCT_IN_PROMOTION'] = $promotion -> promotionList;

								} else {
									$sumOfPromotion[$unique]['PRODUCT_IN_PROMOTION'] = false;
								}

								$sumOfPromotion[$unique]['PROMO_DESC'] = $promotion;
							} else {
								$sumOfPromotion[$unique]['NUMADD'] = $sumOfPromotion[$unique]['NUMADD'] + $ratioGroup;
								$sumOfPromotion[$unique]['NUMADDALL'] = $sumOfPromotion[$unique]['NUMADDALL'] + $numSelect;
							}
						}
					}
				}
			}

			$i++;
		}

		foreach ($sumOfPromotion as $in => $val) {
			$data = $this -> level($in, $val['NUMADD']);
			//print_r($data);exit();
			$sumOfPromotion[$in]['FREE_QTY_PAK'] = $data['FREE_QTY_PAK'];
			$sumOfPromotion[$in]['FREE_QTY_KAR'] = $data['FREE_QTY_KAR'];
			$sumOfPromotion[$in]['FREE_QTY_EA'] = $data['FREE_QTY_EA'];
			$sumOfPromotion[$in]['DISC_AMT'] = $data['DISC_AMT'];
		}

		$this -> data['sumOfPromotion'] = $sumOfPromotion;
		$this -> data['customer'] = $customerData;

		$this -> includeView("addpromotion");
	}

	private function _level($promotionID, $qty) {

		$data['FREE_QTY_PAK'] = 0;
		$data['FREE_QTY_KAR'] = 0;
		$data['FREE_QTY_EA'] = 0;
		$data['DISC_AMT'] = 0;
		$remainQty = $qty;
		$this -> load -> model("promotionmodel");
		$level = $this -> promotionmodel -> getPromotionLevel($promotionID);
		//print_r($level);
		//echo $qty;
		//exit();

		//print_r($level);exit();
		foreach ($level as $in => $val) {

			if ($remainQty > 0) {
				if ($val -> ORDER_UOM == "KAR") {

					$match = ($remainQty == $val -> ORDER_QTY) ? true : false;
					//echo  $val->ORDER_QTY . " % ".$remainQty;
					//echo "<br />";

					if ($match) {

						//echo $val->ORDER_QTY;
						//echo "level is ".$val->PROMO_LEVEL;
						$data['FREE_QTY_' . $val -> FREE_UOM] = $data['FREE_QTY_' . $val -> FREE_UOM] + $val -> FREE_QTY;

						if ($val -> DISC_AMT > 0) {
							$sum = $val -> DISC_AMT * $remainQty;
							$data['DISC_AMT'] = $data['DISC_AMT'] + $sum;
							return $data;
						}
						return $data;

					} else {

						//echo "num is";
					}
				}
			} else {

			}

		}
		return $data;
	}

	private function level($promotionID, $qty) {

		$data['FREE_QTY_PAK'] = 0;
		$data['FREE_QTY_KAR'] = 0;
		$data['FREE_QTY_EA'] = 0;
		$data['DISC_AMT'] = 0;
		$remainQty = $qty;
		$this -> load -> model("promotionmodel");
		$level = $this -> promotionmodel -> getPromotionLevel($promotionID);
		//print_r($level);
		//echo $qty;
		//exit();

		//print_r($level);exit();
		foreach ($level as $in => $val) {

			if ($remainQty > 0) {
				if ($val -> ORDER_UOM == "KAR") {
					$num = floor($remainQty / $val -> ORDER_QTY);

					//echo  $val->ORDER_QTY . " % ".$remainQty;
					//echo "<br />";
					if ($num >= 1) {
						//echo $val->ORDER_QTY;
						//echo "level is ".$val->PROMO_LEVEL;
						$data['FREE_QTY_' . $val -> FREE_UOM] = $data['FREE_QTY_' . $val -> FREE_UOM] + ($val -> FREE_QTY * $num);

						if ($val -> DISC_AMT > 0) {
							
							$sum = $val -> DISC_AMT * $remainQty;
							$data['DISC_AMT'] = $data['DISC_AMT'] + $sum;
						}

						$remainQty = $remainQty - ($num * $val -> ORDER_QTY);

					} else {
						//echo "num is";
					}
				}
			} else {

			}

		}
		return $data;
	}

	private function findPromotionLevel($data, $unit, $qty) {

		$queryRemain = $qty;
		$numAdd = 0;
		$premiumWithUnit = array();
		foreach ($data as $in => $val) {
			if ($val -> ORDER_UOM == $unit) {

				//echo "<br />remain ".$queryRemain;
				//echo "<br />";
				//echo "every". $val -> ORDER_QTY;
				$num = floor($queryRemain / $val -> ORDER_QTY);
				//	echo "<br />receive is ratio ".$num."";
				//echo "<br />receive is * ".$val->FREE_QTY."<br />";

				if ($num > 0) {
					$queryRemain = $queryRemain - ($num * $val -> ORDER_QTY);
					$cal = ($num * $val -> FREE_QTY);
					$numAdd += $cal;
					//echo "<br />receive num = ".$numAdd."<br />";

					// to to heare
					if (!isset($premiumWithUnit[$val -> FREE_UOM])) {
						$premiumWithUnit[$val -> FREE_UOM] = 0;
					}
					$premiumWithUnit[$val -> FREE_UOM] = $premiumWithUnit[$val -> FREE_UOM] + $cal;

					if ($val -> DISC_AMT > 0) {
						$addRate = $val -> DISC_AMT * $num;
						if (isset($premiumWithUnit['DISCOUNT'])) {

							$premiumWithUnit['DISCOUNT'] = $premiumWithUnit['DISCOUNT'] + $addRate;
						} else {
							$premiumWithUnit['DISCOUNT'] = $addRate;
						}

					} else {
						$premiumWithUnit['DISCOUNT'] = 0;
					}
				}

			}
		}

		return $premiumWithUnit;

	}

	private function findPromo($data, $key, $qty) {

		$queryRemain = $qty;
		$premiumQty = 0;
		$arrayPremium = array();
		$totalAdd = 0;
		$unit = "";
		foreach ($data as $in => $val) {
			if ($val -> ORDER_UOM == $key) {
				echo $queryRemain;
				echo "<br />";

				$num = floor($queryRemain / $val -> ORDER_QTY);

				if ($num > 0) {
					$numAdd = ($num * $val -> FREE_QTY);
					$premiumQty += $num;
					$queryRemain -= $num;
					$totalAdd = $totalAdd + $numAdd;

				}
				//echo "Query remain ".$queryRemain;
				//	echo "<br />";
				$unit = $val -> FREE_UOM;
			};
		}
		if ($totalAdd > 0) {
			return array('UNIT' => $unit, 'QTY_ADD' => $totalAdd);
		}
		return false;

		//return $arrayPremium;
	}

	private function _findPromo($data, $key, $qty) {

		if ($key != "KAR") {
			//return "";
		}
		$queryRemain = $qty;
		$premiumQty = 0;
		$arrayPremium = array();
		foreach ($data as $in => $val) {
			if ($val -> ORDER_UOM == $key) {

				//echo $queryRemain;
				//echo "<br />";
				$num = floor($queryRemain / $val -> ORDER_QTY);

				//echo $num;
				//echo "<br />";
				if ($num > 0) {

					//
					// $str = "<br />AT LEVEL ".$val->PROMO_LEVEL;
					// $str.="<br />AT UNIT ".$key;
					// $str.="<br />AFTER QTY ".$queryRemain;
					// $str.="<br />CALQTY ".$num;
					// $str.="<br />ReduceQty ".($num*$val -> ORDER_QTY);
					// $str.="<br />GET ".($num * $val -> FREE_QTY);

					$numAdd = ($num * $val -> FREE_QTY);
					$premiumQty += $numAdd;
					//$str.="<br />PREMIUM ".$premiumQty;
					$queryRemain -= ($num * $val -> ORDER_QTY);
					//$str.="<br />AfterQty".$queryRemain;
					//$str.="<br />--------------------------";
					//echo $str;

					$array = array();
					//echo "<br /><br />OF ".$val->FREE_UOM;
					$a = $ses = $this -> session -> userdata($val -> FREE_UOM);

					//echo "<br />before";
					//print_r($a);
					//echo "<br />numAdd ". $numAdd;
					$a['QTY'] = $a['QTY'] + $numAdd;
					$a['DISCOUNT'] = $a['DISCOUNT'] + ($val -> DISC_AMT * $num);
					//echo "<br />after";
					//print_r($a);
					//print_r($a);
					$this -> session -> set_userdata($val -> FREE_UOM, $a);

					$array['premiumQty'] = $premiumQty;
					$array['UNIT'] = $val -> FREE_UOM;
					$array['DISCOUNT'] = $val -> DISC_AMT;
					$arrayPremium[] = $array;
					/*
					 if($val->DISC_AMT > 0 ){
					 //$discount+= $val->DISC_AMT;
					 }*/
				}
			};
		}

		//return $arrayPremium;
	}

	public function viewCart() {
		$dataPost = $this -> Post2Array($_POST);
		$this -> data['orderID'] = $dataPost['OrderID'];
		$this -> load -> model("ordermodel");
		$this -> data['header'] = "สรุปรายการสั่งซื้อ";
		$custID = $this -> session -> userdata("currentcustomer");

		$this -> data['orderType'] = $this -> ordermodel -> getOrderType();
		$this -> data['orderReason'] = $this -> ordermodel -> getOrderReason();
		$this -> data['itemCategory'] = $this -> ordermodel -> getItemCategory();
		$this -> data['priceType'] = $this -> ordermodel -> getPriceType();

		$this -> load -> model("customermodel");
		$customerData = $this -> customermodel -> getACustomer($custID, "");

		$this -> data['customer'] = $customerData;
		$this -> data['orderType'] = $this -> findValue($this -> data['orderType'], "order_id", "order_name", $this -> session -> userdata('order_type'));
		$this -> data['orderReason'] = $this -> findValue($this -> data['orderReason'], "reason_id", "reason_name", $this -> session -> userdata('order_reason'));
		$this -> data['itemCategory'] = $this -> findValue($this -> data['itemCategory'], "cat_id", "cat_name", $this -> session -> userdata('item_categories'));
		$this -> data['priceType'] = $this -> findValue($this -> data['priceType'], "price_id", "price_type", $this -> session -> userdata('price_type'));
		$this -> includeView("viewcart");
	}

	public function insertOrder() {
		$this -> load -> model("ordermodel");
		$this -> load -> model("customermodel");
		$data = $this -> Post2Array($_POST);

		$customerData = (Array)$this -> customermodel -> getACustomer($data['CustID']);
		$maxID = $this -> ordermodel -> getOrderNum();
		$insert['OrderID'] = "OR-" . date("y") . date("m") . str_pad($maxID + 1, 3, "0", STR_PAD_LEFT);
		$insert['OrderStatus'] = "Taking";
		$insert['CustID'] = $customerData['KUNNR'];
		$insert['CustName'] = $customerData['NAME'];
		$insert['Address1'] = $customerData['ADDRESS'];
		$insert['Telephone'] = $customerData['TELEPHONE'];
		$insert['VatType'] = $data['vatType'];
		$insert['Email'] = $customerData['EMAIL'];
		$insert['Fax'] = $customerData['FAX'];
		$insert['CustType'] = $data['custType'];
		$insert['Payment'] = $data['payment'];
		$insert['CreditRemain'] = $customerData['CREDIT_LEFT'];

		$priceType = "";
		if ($data['CustType'] == "CreditSales") {
			$priceType = "ZPR0";
		} else {
			$priceType = "ZPR1";
		}
		$insert['PriceTypeID'] = $priceType;
		$priceType = $this -> ordermodel -> getPriceTypeID($priceType);
		$insert['PriceTypeName'] = $priceType -> price_type;

		$insert['NumOfProduct'] = 0;
		$insert['SaleID'] = $this -> getSaleID();
		$insert['SaleName'] = $this -> getSaleName();
		$insert['OrderDate'] = date("Y-m-d");
		$insert['CreateOn'] = date("Y-m-d H:i:s");
		$insert['UpdateOn'] = date("Y-m-d H:i:s");
		$this -> ordermodel -> createOrder($insert);
		$this -> cart -> destroy();
		redirect(base_url() . "order/editorder/" . $insert['OrderID']);
		exit();
	}

	public function findValue($data, $key, $value, $values) {
		foreach ($data as $in => $val) {
			$val = (array)$val;
			if ($val[$key] == $values) {
				return $val[$value];
				break;
			}
		}
		return "";
	}

	public function updateCart() {
		$this -> load -> model("productmodel");
		$data = $this -> Post2Array($_POST);
		if (!empty($data)) {
			$qty = $data['qty'];
			$rowID = $data['rowid'];
			$pid = $data['pid'];
			$size = count($rowID);

			/*
			 $column = "";
			 $custType = $data['CustType'];
			 $vatType = $data['VatType'];
			 $this -> session -> set_userdata("vattype", $vatType);
			 if ($custType == "1") {
			 if ($vatType == "v") {
			 $column = "CREDIT_VAT_PRICE";
			 } else {
			 $column = "CREDIT_NOVAT_PRICE";
			 }
			 } else {
			 if ($vatType == "v") {
			 $column = "VAN_VAT_PRICE";
			 } else {
			 $column = "VAN_NOVAT_PRICE";
			 }
			 }
			 */

			for ($i = 0; $i < $size; $i++) {

				if ($rowID[$i] == "0") {

					$cartonQty = $data['cQty'][$i];

					$packQty = $data['pQty'][$i];
					$eqQty = $data['eQty'][$i];
					$checkQty = $cartonQty + $packQty + $eqQty;
					if ($checkQty > 0) {

						$product = $this -> productmodel -> getAProduct($pid[$i]);

						if ($product != false) {

							$cartonQty = $data['cQty'][$i] * $product -> EA_CARTON;
							$packQty = $data['pQty'][$i] * $product -> EA_PACK;
							$eqQty = $data['eQty'][$i] * 1;
							$qty = $cartonQty + $packQty + $eqQty;

							$dataInsert = array('id' => $product -> MATNR, 'qty' => $qty, 'price' => $data['price'][$i], 'name' => "name", 'options' => (array)$product);

							$this -> cart -> insert($dataInsert);

						}
					}

				} else {

					$product = $this -> productmodel -> getAProduct($pid[$i]);
					$cartonQty = $data['cQty'][$i] * $product -> EA_CARTON;
					$packQty = $data['pQty'][$i] * $product -> EA_PACK;
					$eqQty = $data['eQty'][$i] * 1;
					$qty = $cartonQty + $packQty + $eqQty;

					$dataInsert = array('rowid' => $rowID[$i], 'qty' => $qty);
					$this -> cart -> update($dataInsert);
				}
			}
			$this -> set_res("true", "บันทึกข้อมูลเรียบร้อยแล้ว");
		}
	}

	public function updateCartPromotion() {
		$this -> load -> model("productmodel");
		$data = $this -> Post2Array($_POST);
		if (!empty($data)) {
			$qty = $data['qty'];
			$rowID = $data['rowid'];
			$pid = $data['pid'];
			$size = count($rowID);

			for ($i = 0; $i < $size; $i++) {
				if ($rowID[$i] == "0") {
					$cartonQty = $data['cQty'][$i];

					$packQty = $data['pQty'][$i];
					$eqQty = $data['eQty'][$i];
					$checkQty = $cartonQty + $packQty + $eqQty;
					if ($checkQty > 0) {

						$product = $this -> productmodel -> getAProduct($pid[$i]);
						$product -> ISPremium = "Yes";
						if ($product != false) {

							$cartonQty = $data['cQty'][$i] * $product -> EA_CARTON;
							$packQty = $data['pQty'][$i] * $product -> EA_PACK;
							$eqQty = $data['eQty'][$i] * 1;
							$qty = $cartonQty + $packQty + $eqQty;

							$dataInsert = array('id' => $product -> MATNR, 'qty' => $qty, 'price' => $data['price'][$i], 'name' => "name", 'options' => (array)$product);

							$this -> cart -> insert($dataInsert);

						}
					}

				} else {

					$product = $this -> productmodel -> getAProduct($pid[$i]);
					$cartonQty = $data['cQty'][$i] * $product -> EA_CARTON;
					$packQty = $data['pQty'][$i] * $product -> EA_PACK;
					$eqQty = $data['eQty'][$i] * 1;
					$qty = $cartonQty + $packQty + $eqQty;

					$dataInsert = array('rowid' => $rowID[$i], 'qty' => $qty);
					$this -> cart -> update($dataInsert);
				}
			}
			$this -> set_res("true", "บันทึกข้อมูลเรียบร้อยแล้ว");
		}
	}

	public function payment() {
		$this->checkOrderNotEmpty();
		$this -> addJS(array("jquery.ui", "datethai"));
		$this -> load -> model("ordermodel");
		$orderID = $this -> session -> userdata("CORDERID");
		$order = $this -> ordermodel -> getOrderHead($orderID);
		$this -> data['order'] = $order;

		$discount = $this -> session -> userdata("discount-" . $this -> session -> userdata("CORDERID"));
		$this -> data['discount'] = $discount;
		$this -> data['header'] = "ข้อมูลการชำระเงิน";
		$this -> data['DI'] = $this -> session -> userdata("sendID");
		$this -> includeView("payment");
	}

	public function viewordersummary() {
		$this->checkOrderNotEmpty();
		$this -> data['header'] = "ยืนยันการสั่งซื้อ";
		$orderID = $this -> session -> userdata("currentOrderID");

		$this -> load -> model("ordermodel");
		$this -> data['order'] = $this -> ordermodel -> getOrderView($orderID);
		$this -> load -> library('genhtml');
		$this -> data['genhtml'] = $this -> genhtml;
		$paymentStaus = $_POST['paymentStatus'];
		$shipDate = $_POST['shipDate'];
		$this->session->set_userdata("paymentStatus",$paymentStaus);
		$this->session->set_userdata("shipDate",$shipDate);
		
		$this->data['paymentStatus']  = $paymentStaus;
		$this->data['shipDate']  = $shipDate;
		

		$this -> session -> set_userdata("CORDERID", $orderID);
		if ($this -> data['order'] != false) {
			$this -> load -> model("customermodel");
			$customer = $this -> customermodel -> getACustomer($this -> data['order'] -> CustID);

			$this -> session -> set_userdata("currentcustomer", $this -> data['order'] -> CustID);
			$this -> session -> set_userdata("currentOrderID", $orderID);
			$this -> genhtml -> setData($customer);
		}

		$this -> data['DI'] = $this -> session -> userdata("sendID");
		$this -> data['discount'] = $this -> session -> userdata("discount-" . $orderID);
		$this -> includeView("viewordersummary");
	}

	public function tosummaryorder() {
		$this -> load -> model("productmodel");
		$data = $this -> Post2Array($_POST);
		$priceType = $data['priceType'];
		$priceTypeUnit = $data['priceTypeUnit'];

		if (!isset($data['premiumID'])) {
			$data['premiumID'] = array();
		}

		$size = count($data['premiumID']);
		//$this -> deletePremium();
		if ($data['getDiscount'] == "N") {
			$data['discount'] = 0;
		}
		$this -> session -> set_userdata("discount-" . $data['orderid'], $data['discount']);
		$sizeDicount = count($data['discount']);
		$i = 0;

		for ($i = 0; $i < $size; $i++) {
			$rowID = $this -> isPremium($data['premiumID'][$i]);
			if ($rowID == "") {

				$product = $this -> productmodel -> getAProduct($data['premiumID'][$i]);

				if ($product != false) {

					$priceUnit = $product -> $priceTypeUnit;
					$s = explode("/", $priceUnit);
					$pricePerUnit = $s[1];
					if ($pricePerUnit == "CAR") {
						$ratio = $product -> EA_CARTON;
					} else if ($pricePerUnit == "PAC") {
						$ratio = $product -> EA_PACK;
					}
					$price = $product -> $priceType;
					$priceItem = $price / $ratio;

					$eqQty = $data['addEA'][$i] * 1;

					//echo "<br />cartion is".$cartonQty;
					//echo "<br />pack is".$packQty;
					//echo "<br />eqty is".$eqQty;

					$qty = $eqQty;
					$product -> ISPremium = "Yes";

					if ($qty > 0) {
						$dataInsert = array('id' => $product -> MATNR, 'qty' => $qty, 'price' => $data['itemPrice'][$i], 'name' => "name", 'options' => (array)$product);
						$this -> cart -> insert($dataInsert);

					}

				} else {

				}
			} else {
				$c = $this -> cart -> contents();
				$oldQty = $c[$rowID]['qty'];

				$product = $this -> productmodel -> getAProduct($data['premiumID'][$i]);
				$cartonQty = $data['addKAR'][$i] * $product -> EA_CARTON;
				$packQty = $data['addPAK'][$i] * $product -> EA_PACK;
				$eqQty = $data['addEA'][$i] * 1;
				$qty = $cartonQty + $packQty + $eqQty;

				$dataInsert = array('rowid' => $rowID, 'qty' => $qty + $oldQty);
				$this -> cart -> update($dataInsert);
			}
		}

		redirect(base_url() . "order/viewallorder");
	}

	public function out() {
		$this -> cart -> destroy();
	}

	public function summaryDI() {
		$ids = $_POST['pID'];
		$qty = $_POST['sendQty'];
		//$pUnit = $_POST['sendUnit'];
		$itemType = $_POST['itemType'];
		$length = count($ids);
		$allData = array();
		for ($i = 0; $i < $length; $i++) {
			$arr = array();
			$arr['pID'] = $ids[$i];
			$arr['pQty'] = $qty[$i];
			$arr['pUnit'] = "";
			$arr['type'] = $itemType[$i];
			$allData[] = $arr;
		}

		$this -> session -> set_userdata("sendID", $allData);

		redirect(base_url() . "order/payment");
	}

	public function viewallorder() {
		$this->checkOrderNotEmpty();
		$this -> load -> model("ordermodel");
		$orderID = $this -> session -> userdata("CORDERID");
		$order = $this -> ordermodel -> getOrderHead($orderID);
		$this -> data['order'] = $order;

		$discount = $this -> session -> userdata("discount-" . $this -> session -> userdata("CORDERID"));
		$this -> data['discount'] = $discount;
		$this -> data['header'] = "สรุปรายการ Order ทั้งหมด";
		$this -> includeView("viewallorder");
	}

	public function createOrder() {
		$allData = array();
		$orderHead = array();
		$orderID = $this -> session -> userdata("CORDERID");
		$i = 1;
		$productSale = 0;
		$productPremium = 0;
		$totalAmount = 0;
		$totalPremium = 0;

		$AllDiscount = 0;
		$firstSendPrice = 0;
		$totalDiscount = $this -> session -> userdata("discount-" . $this -> session -> userdata("CORDERID"));
		$this->load->model("ordermodel");
		$order = $this->ordermodel->getOrderHead($orderID);
		$DI = $this -> session -> userdata("sendID");
		$paidPrice = 0;
		$DIDetail = array();
		foreach ($this->cart->contents() AS $item) {
			$option = $this -> cart -> product_options($item['rowid']);
			$data = array();
			$discount = 0;
			$qty = $item['qty'];
			$totalDiscount += $discount;
			$pType = "sale";
			if (isset($option['ISPremium']) && $option['ISPremium'] == "Yes") {
				$data['isSaleProduct'] = "TANN";
				$lineAmount = ($item['price'] * $item['qty']);
				$totalPremium += $lineAmount;
				$pType = "premium";
				$productPremium++;
			} else {

				$lineAmount = ($item['price'] * $item['qty']);
				$totalAmount += $lineAmount;

				$data['isSaleProduct'] = "TAN";
				$productSale++;
			}

			$sendQty = $item['qty'] - ($item['qty'] - $DI[$i - 1]['pQty']);
			$sendPrice = $sendQty * $item['price'];
			$data['sendQty'] = 0;
			$data['sendUnit'] = "";
			if ($sendQty > 0 && $pType == "sale") {
				$firstSendPrice += $sendPrice;
			}
			if($sendQty > 0 ){
				$data['sendQty'] = $sendQty;
				$data['sendUnit'] = $DI[$i-1]['pUnit'];
			}
			
			
			
			$data['OrderID'] = $orderID;
			$data['pID'] = $item['id'];
			$data['pName'] = $option['MAKTX'];
			$data['price'] = $item['price'];
			$data['qty'] = $item['qty'];
			$data['discount'] = $AllDiscount;
			$data['LineAmount'] = $lineAmount;
			$data['SaleUnit'] = $option['BASE_UNIT'];
			$data['PackRatio'] = $option['EA_PACK'];
			$data['CartonRatio'] = $option['EA_CARTON'];
			$data['priceAfterDisc'] = $lineAmount - $AllDiscount;
			$docQty = 0;
			if ($option['BASE_UNIT'] == "EA") {
				$docQty = $qty;
			} else if ($option['BASE_UNIT'] == "PAK") {
				$docQty = $qty / $option['EA_PACK'];
			} else {
				$docQty = $qty / $option['EA_CARTON'];
			}
			$data['DocQty'] = $docQty;
			$data['seqNo'] = $i;

			$allData[] = $data;
			$maxID = $this -> ordermodel->getDINum();
			$dino = "DI-" . date("y") . date("m") . str_pad($maxID + 1, 3, "0", STR_PAD_LEFT);
			if($sendQty > 0){
				$data['DINo'] = $dino;
				$data['DocQty'] = $sendQty;
				$data['DocUnit'] = $data['sendUnit'];
				$data['qty'] = $data['DocQty'];
				$data['LineAmount'] = $data['price'] * $data['qty'];
				unset($data['OrderID']);
				unset($data['sendQty']);
				unset($data['sendUnit']);
				unset($data['priceAfterDisc']);
				unset($data['discount']);
				
				
				$DIDetail[] = $data;
			}
			$i++;
		}
		$orderHead['NumOfProduct'] = count($this -> cart -> contents());
		$orderHead['NumOfProductSale'] = $productSale;
		$orderHead['NumOfProductPremium'] = $productPremium;
		$orderHead['TotalAmount'] = $totalAmount;
		$orderHead['Discount'] = $totalDiscount;
		$orderHead['PremiumPrice'] = $totalPremium;
		$orderHead['PriceAfterDisc'] = $totalAmount - $totalDiscount;
		$orderHead['PricePaid'] = $firstSendPrice;
		$orderHead['PaymentStatus'] = $this->session->userdata("paymentStatus");
		if($orderHead['PaymentStatus']=="N"){
			$orderHead['PricePaid']  = 0;	
		}
		
		$this -> load -> model("ordermodel");
		/*
		 * */
		 $order->shipDate = $this->session->userdata("shipDate");
		 
		$this -> ordermodel -> insertOrder($allData, $orderHead,$order,$DIDetail);

		$this -> cart -> destroy();
		$this->session->set_userdata("currentOrderID","");
		
		
		redirect(base_url() . "order/vieworder/?orderid=" . $orderID);
	}

	public function vieworder() {
		$order = $_GET['orderid'];
		$this -> data['header'] = "Order " . $order;
		$this -> load -> model("ordermodel");
		$this -> data['order'] = $this -> ordermodel -> getOrder($order);
		
		$this->data['DI'] = $this->ordermodel->getDIHeadList($order);
		$this -> includeView("vieworder");

	}
	public function viewDI() {
		$dino = $_GET['dino'];
		$this -> data['header'] = "DINO " . $dino;
		$this -> load -> model("ordermodel");
		$this -> data['order'] = $this -> ordermodel -> getDI($dino);
		$this -> includeView("viewdi");

	}
	public function in_cart($product_id = null) {

		if ($this -> cart -> total_items() > 0) {

			$in_cart = array();
			// Fetch data for all products in cart
			foreach ($this->cart->contents() AS $item) {
				$option = $this -> cart -> product_options($item['rowid']);
				$option = (array)$option;
				if (!(isset($option['ISPremium']))) {
					$in_cart[$item['id']] = array("qty" => $item['qty'], "rowid" => $item['rowid']);
				}

			}

			return $in_cart;
		}
		return array();
		;
	}

	public function in_cartPemium($product_id = null) {

		if ($this -> cart -> total_items() > 0) {

			$in_cart = array();
			// Fetch data for all products in cart
			foreach ($this->cart->contents() AS $item) {
				$option = $this -> cart -> product_options($item['rowid']);
				$option = (array)$option;
				if ((isset($option['ISPremium']) && $option['ISPremium'] == 'Yes')) {
					$in_cart[$item['id']] = array("qty" => $item['qty'], "rowid" => $item['rowid']);
				}

			}

			return $in_cart;
		}
		return array();
		;
	}

	public function isPremium($product_id = null) {
		$find = "";
		if ($this -> cart -> total_items() > 0) {

			$in_cart = array();
			// Fetch data for all products in cart
			foreach ($this->cart->contents() AS $item) {
				$option = $this -> cart -> product_options($item['rowid']);
				$option = (array)$option;

				if ($product_id != null) {

					if ($item['id'] == $product_id && (isset($option['ISPremium']) && $option['ISPremium'] == 'Yes')) {
						$find = $item['rowid'];
						break;
					}
				} else {

					if ((isset($option['ISPremium']) && $option['ISPremium'] == 'Yes')) {
						$find = $item['rowid'];
						break;
					}

				}
			}

		}
		return $find;

	}

	public function deletePremium() {
		$id = array();
		if ($this -> cart -> total_items() > 0) {

			$in_cart = array();
			// Fetch data for all products in cart
			foreach ($this->cart->contents() AS $item) {
				$option = $this -> cart -> product_options($item['rowid']);
				$option = (array)$option;

				if (isset($option['ISPremium']) && $option['ISPremium'] == 'Yes') {
					$id[] = $item['rowid'];
				}
			}
		}
		foreach ($id as $i) {
			$data = array('rowid' => $i, 'qty' => 0);
			$this -> cart -> update($data);
		}

	}

	public function addToCart() {

	}

	public function printOrder($orderID) {

		$this -> load -> model("ordermodel");
		$order = $this -> ordermodel -> getOrder($orderID);

		$detail = $order -> orderDetail;

		$this -> load -> helper('pdf_helper');
		tcpdf();

		$x = 5;
		$y = 10;
		$dimen = 5;
		$pdf = new TCPDF();
		// disable header and footer
		$pdf -> setPrintHeader(false);
		$pdf -> setPrintFooter(false);
		$pdf -> SetFont('angsanaupc', '', 14, '', true);
		$pdf -> AddPage();

		$style = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '10,20,5,10', 'phase' => 10, 'color' => array(255, 0, 0));
		$style2 = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(255, 0, 0));
		$style3 = array('width' => 1, 'cap' => 'round', 'join' => 'round', 'dash' => '2,10', 'color' => array(255, 0, 0));
		$style4 = array('L' => 0, 'T' => array('width' => 0.25, 'cap' => 'butt', 'join' => 'miter', 'dash' => '20,10', 'phase' => 10, 'color' => array(100, 100, 255)), 'R' => array('width' => 0.50, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(50, 50, 127)), 'B' => array('width' => 0.75, 'cap' => 'square', 'join' => 'miter', 'dash' => '30,10,5,10'));
		$style5 = array('width' => 0.25, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 64, 128));
		$style6 = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '10,10', 'color' => array(0, 128, 0));
		$style7 = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(255, 128, 0));

		$width = 200;
		$c1 = 3;
		$c2 = 4;
		$boxHeight = 43;
		$bordeRadius = 5;

		//$pdf -> Image('asset/images/logo_invoice.png', 5, 10, 33, 20, 'png', '', '', false, 72, '', false, false, 0, false, false, false);
		$pdf -> Image('asset/images/logo-kohkae.png', 35, 5, 15, 25, 'png', '', '', false, 72, '', false, false, 0, false, false, false);
		$pdf -> Text($x + 45, $y, 'บริษัท โรงงานแม่รวย จำกัด');
		$pdf -> Text($x + 45, $y + 5, '80/9 หมู่ 6 ถนนบางขุนเทียน-ชายทะเล แขวงแสมดำ เขตบางขุนเทียน กรุงเทพฯ 10150');
		$pdf -> Text($x + 45, $y += 10, 'โทร.0-2416-0077, 0-2894-1091 แฟ็กซ์. (662) 415-5924, 416-3082');

		$y += 10;
		$pdf -> SetFont('angsanaupc', '', 24, '', true);
		$newY = $y + 2;
		$pdf -> Text($x + 75, $y += 2, 'ต้นฉบับใบเสร็จรับเงิน');
		$pdf -> Text($x + 81, $y += 6, 'Receipt Original');
		$pdf -> SetFont('angsanaupc', '', 16, '', true);
		$pdf -> Text($x + 87, $y += 10, '(สำหรับลูกค้า)');

		$pdf -> SetFont('angsanaupc', '', 14, '', true);
		$pdf -> Text($x, $y += 10, 'เลขประจำตัวผู้เสียภาษี');
		$y += 8;
		$newY = $y + 2;
		$pdf -> RoundedRect($x, $newY - 2, 115, $boxHeight, $bordeRadius, '1111', 'DF', '', array(255, 255, 255));
		$pdf -> Text($x + 2, $newY, 'รหัสลูกค้า: ' . $order -> CustID);
		$pdf -> Text($x + 2, $newY += $c1, 'Code');

		$pdf -> Text($x + 2, $newY += $c2, 'นามลูกค้า: ' . $order -> CustName);
		$pdf -> Text($x + 2, $newY += $c1, 'Name');
		$pdf -> Text($x + 2, $newY += $c2, 'ที่อยู่: ' . $order -> Address1);
		$pdf -> Text($x + 2, $newY += $c1, 'Address');

		$nexX = $x + 120;
		$xIncornder = $nexX + 2;
		$newY = $y + 2;
		$pdf -> RoundedRect($x + 120, $y, 80, $boxHeight, $bordeRadius, '1111', 'DF', '', array(255, 255, 255));

		$creatOn = Date("d-M-Y", strtotime($order -> CreateOn));
		$pdf -> Text($xIncornder, $newY, 'วันที่: ' . $creatOn);
		$pdf -> Text($xIncornder, $newY += $c1, 'Date');

		$pdf -> Text($xIncornder, $newY += $c2, 'เลขที่: ' . $order -> OrderID);
		$pdf -> Text($xIncornder, $newY += $c1, 'No.');

		$pdf -> Text($xIncornder, $newY += $c2, 'พนักงานขาย: ' . $order -> SaleName);
		$pdf -> Text($xIncornder, $newY += $c1, 'Saleman No.');

		$pdf -> Text($xIncornder, $newY += $c2, 'กำหนดชำระเงิน');
		$pdf -> Text($xIncornder, $newY += $c1, 'Term');

		$pdf -> Text($xIncornder, $newY += $c2, 'ครบกำหนดวันที่');
		$pdf -> Text($xIncornder, $newY += $c1, 'Due Date');

		// end order head;
		$y = ($y + $boxHeight) + $dimen;
		$coldWidth = array(0.2, 0.35, 0.10, 0.10, 0.10, 0.15);
		$rowHeadHeight = 12;
		$newY = $y;
		$newX = $x;
		$newYText = $y + 2;
		$column = 6;

		$pdf -> RoundedRect($x, $newY, $width * $coldWidth[0], $rowHeadHeight, $bordeRadius, '0001', 'DF', '', array(255, 255, 255));

		$pdf -> Text($newX + 6, $newYText, 'รหัสสินค้า');
		$pdf -> Text($newX + 5, $newYText + $c1, 'Product Code');

		$pdf -> RoundedRect($newX += $width * $coldWidth[0], $newY, $width * $coldWidth[1], $rowHeadHeight, $bordeRadius, '0000', 'DF', '', array(255, 255, 255));
		$pdf -> Text($newX + 30, $newYText, 'รายละเอียด');
		$pdf -> Text($newX + 30, $newYText + $c1, 'Description');

		$pdf -> RoundedRect($newX += $width * $coldWidth[1], $newY, $width * $coldWidth[2], $rowHeadHeight, $bordeRadius, '0000', 'DF', '', array(255, 255, 255));
		$pdf -> Text($newX + 5, $newYText, 'จำนวน');
		$pdf -> Text($newX + 4, $newYText + $c1, 'Quantity');

		$pdf -> RoundedRect($newX += $width * $coldWidth[2], $newY, $width * $coldWidth[3], $rowHeadHeight, $bordeRadius, '0000', 'DF', '', array(255, 255, 255));
		$pdf -> Text($newX + 4, $newYText, 'หน่วยละ');
		$pdf -> Text($newX + 3, $newYText + $c1, 'Unit/Price');

		$pdf -> RoundedRect($newX += $width * $coldWidth[3], $newY, $width * $coldWidth[4], $rowHeadHeight, $bordeRadius, '0000', 'DF', '', array(255, 255, 255));
		$pdf -> Text($newX + 4, $newYText, 'ส่วนลด');
		$pdf -> Text($newX + 3, $newYText + $c1, 'Discount');

		$pdf -> RoundedRect($newX += $width * $coldWidth[4], $newY, $width * $coldWidth[5], $rowHeadHeight, $bordeRadius, '1000', 'DF', '', array(255, 255, 255));
		$pdf -> Text($newX + 7, $newYText, 'จำนวนเงิน');
		$pdf -> Text($newX + 8, $newYText + $c1, 'Amount');

		$maxLine = 11;
		$orderLine = count($detail);
		$emptyLinje = $maxLine - $orderLine;

		$emptyX = $x;

		$newY = $newY + $rowHeadHeight;
		$emptyY = $newY;
		$emptyStyle = array('L' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'T' => 0, 'R' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'B' => 0);

		$beforeEnd = array('L' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'T' => 0, 'R' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'B' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'));

		$endStyle = array('L' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'T' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'R' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'), 'B' => array('width' => 0.25, 'cap' => 'square', 'join' => 'miter', 'solid' => '30,10,5,10'));

		$productHeight = 8;
		foreach ($detail as $in => $val) {
			$emptyX = $x;
			$array = array();
			$array[] = $val -> pID;
			$array[] = $val -> pName;
			$array[] = number_format($val -> Qty, 0);
			$array[] = number_format($val -> Price, 2);
			$array[] = number_format($val -> Discount, 2);
			$array[] = number_format($val -> PriceAfterDisc, 2);

			$align = array();
			$align[] = "L";
			$align[] = "L";
			$align[] = "R";
			$align[] = "R";
			$align[] = "R";
			$align[] = "R";

			$textX = 0;
			for ($j = 0; $j < $column; $j++) {
				$index = $j - 1;
				if ($index < 0) {
					$r = 0;
				} else {
					$r = $coldWidth[$index];
				}
				$pdf -> RoundedRect($emptyX += $width * $r, $emptyY, $width * $coldWidth[$j], $productHeight, $bordeRadius, '0000', 'DF', $emptyStyle, array(255, 255, 255));

				if ($align[$j] == "R") {
					//$textX = 0;
					$pdf -> TextRight(($textX += ($width * $r)) + 4, $emptyY, $width * $coldWidth[$j], $array[$j]);
				} else {

					$pdf -> Text(($textX += ($width * $r)) + 8, $emptyY, $array[$j]);
				}

			}
			$emptyY += $productHeight;

		}

		for ($i = 0; $i < $emptyLinje - 1; $i++) {
			$emptyX = $x;

			for ($j = 0; $j < $column; $j++) {
				$index = $j - 1;
				if ($index < 0) {
					$r = 0;
				} else {
					$r = $coldWidth[$index];
				}

				$pdf -> RoundedRect($emptyX += $width * $r, $emptyY, $width * $coldWidth[$j], $productHeight, $bordeRadius, '0000', 'DF', $emptyStyle, array(255, 255, 255));
			}
			$emptyY += $productHeight;
		}
		/*
		 for($i=0;$i<1;$i++){
		 $emptyX = $x;
		 for($j=0;$j<$column;$j++){
		 $index = $j-1;
		 if($index < 0 ){
		 $r = 0;
		 }else{
		 $r  = $coldWidth[$index];
		 }
		 $pdf->RoundedRect($emptyX+= $width * $r, $emptyY, $width * $coldWidth[$j], $rowHeadHeight, $bordeRadius, '0000', 'DF', $beforeEnd ,array(255,255,255));
		 }
		 $emptyY+=$rowHeadHeight;
		 }*/
		$emptyX = $x;
		$mergWidth = ($width * $coldWidth[0]) + ($width * $coldWidth[1]) + ($width * $coldWidth[2]);
		$mergWidth2 = ($width * $coldWidth[3]) + ($width * $coldWidth[4]);
		$mergWidth3 = ($width * $coldWidth[5]);
		$pdf -> RoundedRect($emptyX, $emptyY, $mergWidth, $rowHeadHeight, $bordeRadius, '0010', 'DF', $endStyle, array(255, 255, 255));

		if ($order -> VatType == "VAT") {
			//ราคาขาย - (ราคาขาย คูณด้วย 7 หารด้วย 107)  ลองดูนะครับ
			$netAmount = $order -> PriceAfterDisc;
			$vatPrice = (($order -> PriceAfterDisc * 7) / 107);
			$totalAmount = $netAmount - $vatPrice;

		} else {
			$netAmount = $order -> PriceAfterDisc;
			$vatPrice = 0;
			$totalAmount = $netAmount - $vatPrice;

		}

		$pdf -> RoundedRect($emptyX += $mergWidth, $emptyY, $mergWidth2, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle, array(255, 255, 255));
		$leftTextToal = $emptyX;
		$pdf -> Text($leftTextToal + 15, $emptyY + 1, 'รวมเงิน');
		$pdf -> Text($leftTextToal + 14, $emptyY + $c1 + 2, 'Sub Total');
		$pdf -> RoundedRect($emptyX += $mergWidth2, $emptyY, $mergWidth3, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> TextRight($emptyX, $emptyY + $c1, $mergWidth3, number_format($totalAmount, 2));

		$leftX = $x;
		$sartY = $emptyY + $rowHeadHeight + 2;
		$pdf -> RoundedRect($leftX, $sartY, $mergWidth - 2, $rowHeadHeight + 11, $bordeRadius, '1001', 'DF', $endStyle, array(255, 255, 255));

		$pdf -> Text($leftX + 2, $sartY + 1, 'การชำระเงิน');

		$pdf -> RoundedRect($leftX + 3, $sartY += 9, 3, 3, 0, '0000', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> Text($leftX += 8, $sartY - 2, 'เงินสด');

		$pdf -> RoundedRect($leftX += 15, $sartY, 3, 3, 0, '0000', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> Text($leftX += 5, $sartY - 2, 'โอนเข้าธนาคาร........................................ อื่น ๆ..........................................');

		$sartY += 7;
		$leftX = $x;
		$pdf -> RoundedRect($leftX += 3, $sartY, 3, 3, 0, '0000', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> Text($leftX += 5, $sartY - 2, 'เช็ค/ดราฟธนาคาร.....................สาขา......................เลขที่.......................ลงวันที่..................');

		$leftX = $x;
		$sartY = $emptyY + $rowHeadHeight + 2;
		$boxY = $sartY + $rowHeadHeight + 11;
		$pdf -> RoundedRect($leftX, $boxY, $mergWidth - 2, $rowHeadHeight + 18, $bordeRadius, '0110', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> Text($leftX + 2, $boxY + 5, '..................................................................');
		$pdf -> Text($leftX + 70, $boxY + 5, '.................................................................');

		$pdf -> Text($leftX + 18, $boxY + 10, 'ผู้รับเงิน /Collector');
		$pdf -> Text($leftX + 90, $boxY + 10, 'วันที่ /Date');

		$pdf -> Text($leftX + 2, $boxY + 18, 'หมายเหตุ: ใบเสร็จรับเงินนี้จะสมบูรณ์เมื่อมีลายเซ็นของผู้อนุมัติและผู้รับเงินลงรายมือร่วมกัน');
		$pdf -> Text($leftX + 17, $boxY + 23, 'และบริษัทฯ ได้เรียกเก็บเงินตามเช็คจากธนาคารถูกต้องเรียบร้อยแล้ว');

		$emptyY += $rowHeadHeight;
		$emptyX = $emptyX - $mergWidth2;
		$pdf -> RoundedRect($emptyX, $emptyY, $mergWidth2, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> Text($leftTextToal + 10, $emptyY + 1, 'ภาษีมูลค่าเพิ่ม');
		$pdf -> Text($leftTextToal + 14, $emptyY + $c1 + 2, 'V.A.T');

		$pdf -> RoundedRect($emptyX += $mergWidth2, $emptyY, $mergWidth3, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle, array(255, 255, 255));

		$pdf -> TextRight($emptyX, $emptyY + $c1, $mergWidth3, number_format($vatPrice, 2));

		$emptyY += $rowHeadHeight;
		$emptyX = $emptyX - $mergWidth2;
		$pdf -> RoundedRect($emptyX, $emptyY, $mergWidth2, $rowHeadHeight, $bordeRadius, '0010', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> Text($leftTextToal + 12, $emptyY + 1, 'ยอดเงินสุทธิ');
		$pdf -> Text($leftTextToal + 11, $emptyY + $c1 + 2, 'Net Amount');
		$pdf -> RoundedRect($emptyX += $mergWidth2, $emptyY, $mergWidth3, $rowHeadHeight, $bordeRadius, '0100', 'DF', $endStyle, array(255, 255, 255));
		$pdf -> TextRight($emptyX, $emptyY + $c1, $mergWidth3, number_format($netAmount, 2));

		$pdf -> RoundedRect($emptyX - $mergWidth2, $emptyY + $rowHeadHeight + 2, $mergWidth2 + $mergWidth3, $rowHeadHeight + 16, $bordeRadius, '1111', 'DF', $endStyle, array(255, 255, 255));

		$pdf -> Text($emptyX - $mergWidth2 + 3, $emptyY + $rowHeadHeight + 8, 'ในนามบริษัท...........................................จำกัด');

		//$pdf->RoundedRect($emptyX+=$mergWidth2, $emptyY, $mergWidth3, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle ,array(255,255,255));
		/*
		 $pdf->RoundedRect($emptyX+=$mergWidth, $emptyY, $mergWidth2, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle ,array(255,255,255));

		 $pdf->RoundedRect($emptyX+=$mergWidth2, $emptyY, $mergWidth3, $rowHeadHeight, $bordeRadius, '0000', 'DF', $endStyle ,array(255,255,255));

		 */

		$pdf -> Output('printorder-' . $orderID . '.pdf', 'I');
		$this -> load -> view('printorder', $data);
	}

	public function templateOrder() {
		$data = array();
		$this -> load -> view('templateorder', $data);
	}
	public function checkOrderNotEmpty(){
		if($this->cart->total_items() <=0){
			redirect(base_url() . "order/");
			exit();
		}
		
	}

	/*
	 *
	 * */
}
?>